package com.xywl.escort.view.address;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.xywl.escort.R;
import com.xywl.escort.adapter.ManageAddressAdapter;
import com.xywl.escort.base.BaseActivity;
import com.xywl.escort.bean.AddrBean;
import com.xywl.escort.bean.AddrListResp;
import com.xywl.escort.bean.AddrReq;
import com.xywl.escort.bean.BaseResp;
import com.xywl.escort.bean.DelAddressReq;
import com.xywl.escort.utils.ToastUtil;
import com.xywl.escort.widget.HorizontalDividerItemDecoration;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import dagger.android.AndroidInjection;

@Route(path = "/xy/address/manage")
public class ManageAddressActivity extends BaseActivity implements ManageAddressContract.View, SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.recycler_address)
    RecyclerView mRecyclerAddress;
    @BindView(R.id.progress_bar)
    ProgressBar mProgressBar;
    @BindView(R.id.btn_add_address)
    Button mBtnAddAddress;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    private List<AddrBean> mDataBeanList = new ArrayList<>();
    private ManageAddressAdapter mAdapter;

    @Inject
    ManageAddressContract.Presenter mPresenter;

    @Autowired
    int type;

    private int pageNum = 1;
    private boolean isEnd = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        AndroidInjection.inject(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_manage_address);
        ARouter.getInstance().inject(this);
        ButterKnife.bind(this);

        showBackButton();
        setTitleText("管理收货地址");

        mAdapter = new ManageAddressAdapter(R.layout.item_manage_address, mDataBeanList);
        mRecyclerAddress.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerAddress.setAdapter(mAdapter);

        View emptyView = LayoutInflater.from(this).inflate(R.layout.layout_empty_view, null);
        TextView tvEmpty = emptyView.findViewById(R.id.tv_empty);
        tvEmpty.setText("暂无收货地址");
        mAdapter.setEmptyView(emptyView);

        final Paint paint = new Paint();
        paint.setStrokeWidth(1);
        paint.setColor(ContextCompat.getColor(this, R.color.line_color));
        paint.setAntiAlias(true);
        mRecyclerAddress.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this).paint(paint).build());

        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setColorSchemeResources(R.color.colorAccent, R.color.colorPrimary, R.color.aid_prompt_color, R.color.colorBackground);
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                AddrBean address = mDataBeanList.get(position);
                switch (view.getId()) {
                    case R.id.layout_set_default: {
                        AddrReq req = new AddrReq();
                        req.id = address.id;
                        req.isDefault = 1;
                        mPresenter.updateAddressStatus(req);
                    }
                    break;
                    case R.id.tv_edit: {
                        ARouter.getInstance().build("/xy/address/add")
                                .withInt("type", 1)
                                .withString("id", address.id)
                                .withObject("bean", address)
                                .navigation();
                    }
                    break;
                    case R.id.tv_delete: {
                        String id = address.id;
                        DelAddressReq req = new DelAddressReq();
                        req.ids = id;
                        mPresenter.delAddress(req);
                    }
                    break;
                    default:
                        break;
                }
            }
        });

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (type == 1) {
                    AddrBean address = mDataBeanList.get(position);
                    Intent intent = new Intent();
                    intent.putExtra("address", address);
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }
        });

        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mSwipeRefreshLayout.setEnabled(false);
                mRecyclerAddress.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mSwipeRefreshLayout.setEnabled(false);
                        if (isEnd) {
                            //数据全部加载完毕
                            mAdapter.loadMoreEnd();
                            mSwipeRefreshLayout.setEnabled(true);
                        } else {
                            //成功获取更多数据
                            mPresenter.loadAddressList(pageNum);
                        }
                    }
                }, 200);
            }
        }, mRecyclerAddress);
    }

    @Override
    protected void onResume() {
        super.onResume();

        pageNum = 1;
        mPresenter.takeView(this);
        mPresenter.loadAddressList(pageNum);
    }

    @Override
    public boolean isActive() {
        return false;
    }

    @Override
    public <T> LifecycleTransformer<T> bindToLife() {
        return this.<T>bindToLifecycle();
    }

    @Override
    public void onRefresh() {
        mAdapter.setEnableLoadMore(false);
        pageNum = 1;
        mPresenter.loadAddressList(pageNum);
    }

    @Override
    public void loadAddressListFailure() {
        mProgressBar.setVisibility(View.GONE);
        mSwipeRefreshLayout.setRefreshing(false);
        mRecyclerAddress.setVisibility(View.VISIBLE);
        mBtnAddAddress.setVisibility(View.VISIBLE);
    }

    @Override
    public void loadAddressListSuccess(AddrListResp resp) {
        mProgressBar.setVisibility(View.GONE);
        mSwipeRefreshLayout.setRefreshing(false);
        mRecyclerAddress.setVisibility(View.VISIBLE);
        mBtnAddAddress.setVisibility(View.VISIBLE);
        if (null != resp.data && null != resp.data.list) {
            List<AddrBean> list = resp.data.list;
            if (pageNum == 1) {
                mDataBeanList.clear();
            }
            mDataBeanList.addAll(list);
            if (pageNum >= resp.data.pages) {
                isEnd = true;
            } else {
                isEnd = false;
                pageNum += 1;
            }
            mAdapter.setNewData(mDataBeanList);
            mAdapter.loadMoreComplete();
            mSwipeRefreshLayout.setEnabled(true);
        }
    }

    @Override
    public void updateAddressSuccess(BaseResp resp) {
        mAdapter.setEnableLoadMore(false);
        pageNum = 1;
        mPresenter.loadAddressList(pageNum);
    }

    @Override
    public void updateAddressFailure(String msg) {
        ToastUtil.showTip(this, msg);
    }

    @Override
    public void delAddressSuccess(BaseResp req) {
        ToastUtil.showTip(this, "删除收货地址成功");
        mAdapter.setEnableLoadMore(false);
        pageNum = 1;
        mPresenter.loadAddressList(pageNum);
    }

    @Override
    public void delAddressFailure(String msg) {
        ToastUtil.showTip(this, msg);
    }

    @OnClick(R.id.btn_add_address)
    public void onViewClicked() {
        ARouter.getInstance().build("/xy/address/add").withInt("type", 0).navigation();
    }
}
